﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Singleton
{
    public class Singleton<T> where T: class
    {
        /// <summary>
        /// Protected constructor
        /// </summary>
        protected Singleton() { }

        /// <summary>
        /// T class object
        /// </summary>
        private static T instance;

        /// <summary>
        /// Key for thread safe
        /// </summary>
        private static object key = new object();

        /// <summary>
        /// Return T class object or create new if it doesn't exist
        /// </summary>
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (key)
                    {
                        var constructor = typeof (T).GetConstructors();
                        var result = constructor[0].Invoke(null);

                        instance = (T) result;
                    }
                }

                return instance;
            }
        }
    }
}
